package crp.services.api.graphql.loaders;

import com.qwlabs.lang.C2;
import crp.core.academic.app.AcademicService;
import crp.core.academic.domain.models.AcademicTermEntity;
import crp.services.api.graphql.models.AcademicTermPayload;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;

@ApplicationScoped
public class AcademicFetcher {
    private final AcademicService academicService;

    @Inject
    public AcademicFetcher(AcademicService academicService) {
        this.academicService = academicService;
    }

    public List<AcademicTermPayload> fetchTerms(List<String> ids) {
        Map<String, AcademicTermPayload> mapping = C2.map(academicService.searcher().termsByIds(ids),
                AcademicTermEntity::getId,
                AcademicTermPayload::of);
        return C2.list(ids, mapping::get);
    }

    public <S> List<AcademicTermPayload> fetchTerms(List<S> sources, Function<S, String> idMapper) {
        Set<String> ids = C2.set(sources, idMapper, Objects::nonNull);
        Map<String, AcademicTermPayload> mapping = C2.map(academicService.searcher().termsByIds(ids),
                AcademicTermEntity::getId,
                AcademicTermPayload::of);
        return C2.list(sources, source ->
                Optional.ofNullable(idMapper.apply(source))
                        .map(mapping::get)
                        .orElse(null));
    }
}
